package com.nbcio.cd.config;

import com.nbcio.cd.domain.CdFolder;
import com.nbcio.cd.domain.CdUserStorage;
import com.nbcio.cd.mapper.CdFolderMapper;
import com.nbcio.cd.mapper.CdUserStorageMapper;
import com.nbcio.common.satoken.utils.LoginHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 云网盘初始化配置
 * 系统启动时自动为用户创建根文件夹和存储统计
 *
 * @author nbacheng
 * @date 2024-01-01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CdInitializer implements CommandLineRunner {

    private final CdFolderMapper cdFolderMapper;
    private final CdUserStorageMapper cdUserStorageMapper;

    @Override
    public void run(String... args) throws Exception {
        log.info("云网盘模块初始化开始...");
        
        // 初始化配置
        initializeDefaultConfig();
        
        log.info("云网盘模块初始化完成");
    }

    /**
     * 初始化默认配置
     */
    private void initializeDefaultConfig() {
        log.info("初始化云网盘默认配置...");
        
        // 这里可以添加一些默认配置的初始化逻辑
        // 例如：初始化默认存储限制、文件类型等
        
        log.info("云网盘默认配置初始化完成");
    }

    /**
     * 为用户创建根文件夹（在用户首次使用云网盘时调用）
     */
    public void createUserRootFolder(Long userId) {
        try {
            // 检查用户根文件夹是否已存在
            CdFolder existingFolder = cdFolderMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdFolder>()
                    .eq(CdFolder::getOwnerId, userId)
                    .eq(CdFolder::getParentId, 0L)
                    .eq(CdFolder::getDelFlag, "0")
            );
            
            if (existingFolder != null) {
                log.info("用户根文件夹已存在: userId={}", userId);
                return;
            }
            
            // 创建用户根文件夹
            CdFolder rootFolder = new CdFolder();
            rootFolder.setFolderName("我的文件");
            rootFolder.setParentId(0L);
            rootFolder.setFolderPath("/" + userId);
            rootFolder.setFolderType("personal");
            rootFolder.setOwnerId(userId);
            rootFolder.setFolderSize(0L);
            rootFolder.setFileCount(0);
            rootFolder.setFolderCount(0);
            rootFolder.setIsShared(false);
            rootFolder.setAccessLevel("private");
            rootFolder.setStatus("0");
            rootFolder.setCreateBy(userId);
            rootFolder.setCreateTime(new Date());
            
            cdFolderMapper.insert(rootFolder);
            
            log.info("用户根文件夹创建成功: userId={}", userId);
            
        } catch (Exception e) {
            log.error("创建用户根文件夹失败: userId={}, error={}", userId, e.getMessage(), e);
        }
    }

    /**
     * 初始化用户存储统计（在用户首次使用云网盘时调用）
     */
    public void initUserStorage(Long userId) {
        try {
            // 检查用户存储统计是否已存在
            CdUserStorage existingStorage = cdUserStorageMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CdUserStorage>()
                    .eq(CdUserStorage::getUserId, userId)
                    .eq(CdUserStorage::getDelFlag, "0")
            );
            
            if (existingStorage != null) {
                log.info("用户存储统计已存在: userId={}", userId);
                return;
            }
            
            // 创建用户存储统计
            CdUserStorage userStorage = new CdUserStorage();
            userStorage.setUserId(userId);
            userStorage.setTotalSize(5L * 1024 * 1024 * 1024); // 默认5GB
            userStorage.setUsedSize(0L);
            userStorage.setFileCount(0);
            userStorage.setFolderCount(1); // 包含根文件夹
            userStorage.setStatus("0");
            userStorage.setCreateBy(userId);
            userStorage.setCreateTime(new Date());
            
            cdUserStorageMapper.insert(userStorage);
            
            log.info("用户存储统计初始化成功: userId={}", userId);
            
        } catch (Exception e) {
            log.error("初始化用户存储统计失败: userId={}, error={}", userId, e.getMessage(), e);
        }
    }
}
